package com.lz.springboot.redis;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;

@Component
@EnableApolloConfig({ "Java.redis" })
@PropertySource(value = "classpath:redis.properties", ignoreResourceNotFound = true)
public class ApolloConfigRedis {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigRedis.class);
	@ApolloConfig("Java.redis")
	private Config config;

	//Redis数据库索引（默认为0）
	@Value("${spring.redis.database:0}")
	private Integer database;
	//Redis服务器地址
	@Value("${spring.redis.host:127.0.0.1}")
	private String host;
	//Redis服务器连接端口
	@Value("${spring.redis.port:6379}")
	private Integer port;
	//Redis服务器连接密码（默认为空）
	@Value("${spring.redis.password:}")
	private String password;
	//连接池最大连接数（使用负值表示没有限制）
	@Value("${spring.redis.pool.max-active:8}")
	private Integer maxActive;
	//连接池最大阻塞等待时间（使用负值表示没有限制）
	@Value("${spring.redis.pool.max-wait:-1}")
	private Integer maxWait;
	//连接池中的最大空闲连接
	@Value("${spring.redis.pool.max-idle:8}")
	private Integer maxIdle;
	//连接池中的最小空闲连接
	@Value("${spring.redis.pool.min-idle:0}")
	private Integer minIdle;
	//连接超时时间（毫秒）
	@Value("${spring.redis.timeout:1000}")
	private Integer timeout;

	@ApolloConfigChangeListener("Java.redis")
	private void anotherOnChange(ConfigChangeEvent changeEvent) {
		Set<String> configNames = config.getPropertyNames();
		for (String configName : configNames) {
			LOGGER.info("configName=[{}] configValue=[{}]", configName, config.getProperty(configName, ""));
		}
		if (changeEvent.isChanged("spring.redis.host")) {
			ConfigChange change = changeEvent.getChange("spring.redis.host");
			LOGGER.info("Found change - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(),
					change.getOldValue(), change.getNewValue(), change.getChangeType());
		}
	}
	
	
	@Override
	public String toString() {
		return "RedisConfig [database=" + database + ", host=" + host + ", port=" + port
				+ ", password=" + password + ", maxActive=" + maxActive + ", maxWait=" + maxWait + ", maxIdle="
				+ maxIdle + ", minIdle=" + minIdle + ", timeout=" + timeout + "]";
	}
	
}